package com.csc.finalproject.service;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.ModelMap;

import com.csc.finalproject.dao.RoleDAO;
import com.csc.finalproject.dao.UserDAO;
import com.csc.finalproject.domain.AccountInfo;
import com.csc.finalproject.domain.Role;
import com.csc.finalproject.domain.User;

/**
 * 
 * @author Nguyen Ngoc Truc Giang
 * @since 19/8
 *
 */
@Service("userService")
public class UserServiceImpl implements UserService {
	@Autowired
	private UserDAO userDAO;
	
	@Autowired
	private RoleDAO roleDAO;

	public List<User> getUsers() {
		return userDAO.getAll();
	}

	public int checkLogin(String username, String password,
			HttpServletRequest request) {
		ModelMap model = null;

		List<User> users = userDAO.getAll();
		for (User user : users) {
			if (user.getLogin().equals(username)
					&& (user.getPassword().equals(password))) {
				HttpSession session = request.getSession();
				session.setAttribute("user", user.getLogin());
				if (user.getRole().getId() == 1) {
					return 1;
				} else if (user.getRole().getId() == 2) {
					return 2;
				}
			}
		}
		return 0;
	}

	@Override
	public boolean editUser() {
		return false;
	}

	@Override
	public boolean addUser(String username, String psw) {
		User user = new User();
		user.setLogin(username);
		user.setPassword(psw);
		
		Role role = roleDAO.find(2);
		user.setRole(role);
		userDAO.create(user);
		return true;

	}

	@Override
	public User getUser(int id) {
		User user = userDAO.find(id);
		return user;
	}

}
